﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebTest.Core.Entities.OrderAggregate;
using WebTest.Core.Interfaces;
using WebTest.Infrastructure.Interfaces;

namespace WebTest.Core.Services
{
    public class OrderService : IOrderService
    {
        private readonly IRepository<Order> repository;

        public OrderService(IRepository<Order> repository)
        {
            this.repository = repository ?? throw new ArgumentNullException(nameof(repository));
        }
        public async Task AddAsync(Order order, CancellationToken cancellationToken = default)
        {
            await repository.AddAsync(order, cancellationToken);
        }
        public async Task DeleteAsync(Guid id)
        {
            var order = await repository.SingleOrDefault(x => x.Id == id);
            if(order != null)
            {
                await repository.DeleteAsync(order);
            }
        }
        public async Task DeleteAsync(Order order)
        {
            await repository.DeleteAsync(order);
        }
        public async Task DeleteRangeAsync(List<int> list)
        {
            await repository.DeleteRangeAsync(list);
        }

        public async Task<IReadOnlyCollection<Order>> GetOrderListAsync(Expression<Func<Order, bool>> predicate, CancellationToken cancellationToken = default)
        {
            return await repository.ToListAsync(predicate, cancellationToken);
        }
        public async Task<IReadOnlyCollection<Order>> GetOrderListAsync(int pageSize = 20, int current = 1, CancellationToken cancellationToken = default)
        {
            return await repository.ToListAsync(pageSize, current, cancellationToken);
        }

        public async Task<Order> GetOrderByIdAsync(Guid id, CancellationToken cancellationToken = default)
        {
            return await repository.SingleOrDefault(x => x.Id == id, cancellationToken);
        }

        public async Task<Order> UpdateOrderAsync(Order order, CancellationToken cancellationToken = default)
        {
            return await repository.UpdateAsync(order, cancellationToken);
        }
        public async Task DeleteOrderItemAsync(Guid id, OrderItem orderItem, CancellationToken cancellationToken = default)
        {
            var order = await GetOrderByIdAsync(id, cancellationToken);
            order.RemoveOrderItem(orderItem);
            await UpdateOrderAsync(order, cancellationToken);
        }
        public async Task<Order> LastOrderAsync(CancellationToken cancellationToken = default)
        {
            return await repository.LastOrderAsync(cancellationToken);
        }
    }
}
